package com.sxt.config;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

import com.sxt.entity.SysUser;
import com.sxt.service.SysUserService;


@Configuration
public class UserRealm extends AuthorizingRealm {

	@Autowired
	private SysUserService sysUserService ;
	/**
	 * 授权
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		return null;
	}

	/**
	 * 认证
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		UsernamePasswordToken usernamePassword = (UsernamePasswordToken)token;
		// 1 使用用户名查询用户
		String username = usernamePassword.getUsername();
		SysUser user = sysUserService.findUserByUsername(username);
		if(user==null) {
			return null ; // shiro 能自动处理-> 账号不存在的异常
		}
		ByteSource credentialsSalt = ByteSource.Util.bytes("whsxt"); // 一般盐也来自数据库
		return new SimpleAuthenticationInfo(user, user.getPassword(), credentialsSalt , username);
	}

}
